<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
               :upload-error="loadError"
               v-if="showMain"
    >
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.zyhd_delete"
                   @click="handleDelete">删 除
        </el-button>
        <UploadStyle
          ref="uploadStyle"
          v-if="screenShotDialogVisible"
          :visible="screenShotDialogVisible"
          :img-url="imgUrl"
          :proportion="proportion"
          @closeDialog="closeDialog"
          @getImgURL="getImgURL"
        />
      </template>

      <template slot-scope="{type,size,row,index}" slot="menuBtn">
        <el-dropdown-item divided @click.native="showCyjl(row,index)">报名记录</el-dropdown-item>
      </template>
    </avue-crud>
    <ZyhdCyjl v-bind:activityId="activityId" :showMainView="showMainView" v-if="!showMain" ref="eps"></ZyhdCyjl>
  </basic-container>
</template>

<script>
import {getList, add, update, remove} from "@/api/service/zyhd";
import {mapGetters} from "vuex";

import ZyhdCyjl from "@/views/service/zyhdcyjl";
import {contrastTime} from "@/util/validate";

export default {
  components: {
    ZyhdCyjl
  },
  data() {
    return {
      screenShotDialogVisible: false,
      imgUrl: "",
      _done: null,
      proportion: [200,200],// 宽高的像素数组
      _uploadLoading: null,
      activityId: "",
      showMain: true,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        dialogWidth: "70%",
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuType: 'menu',
        menuBtnTitle: '更多操作',
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "学校名称",
            prop: "schoolId",
            search: false,
            rules: [{
              required: true,
              message: "请选择学校",
              trigger: "blur"
            }],
            type: "tree",
            dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
            props: {
              label: "xxName",
              value: "id"
            },
          },
          {
            label: "标题",
            prop: "title",
            search: true,
            overHidden: true,
            span: 12,
            rules: [{
              required: true,
              message: "请输入标题",
              trigger: "blur"
            }],
            maxlength: 50,
            showWordLimit: true
          },
          {
            label: "简介",
            prop: "intro",
            type: "textarea",
            span: 24,
            minRows: 6,
            rules: [{
              required: true,
              message: "请输入简介",
              trigger: "blur"
            }],
            hide: true,
            maxlength: 200,
            showWordLimit: true
          },
          {
            label: "招募人数",
            prop: "recruitnumber",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入招募人数",
              trigger: "blur"
            }],
            value: 10,
            type: 'number'
          },
          {
            label: "活动地点",
            prop: "location",
            span: 12,
            rules: [{
              required: true,
              message: "请输入活动地点",
              trigger: "blur"
            }],
            hide: true,
            maxlength: 200,
            showWordLimit: true
          },
          {
            label: "报名开始时间",
            prop: "starttime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入报名开始时间",
              trigger: "blur"
            }]
          },
          {
            label: "报名截止时间",
            prop: "endtime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",

            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入报名截止时间",
              trigger: "blur"
            }]
          },
          {
            label: "比赛时间",
            prop: "matchtime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入比赛时间",
              trigger: "blur"
            }]
          },
          {
            label: "活动信息",
            prop: "information",
            span: 24,
            component: "avueUeditor",
            //wangEditor编辑的配置
            customConfig: {
              lineHeights: ['1', '1.15', '1.6', '2', '2.5', '3']
            },
            //是否启用oss(qiniu/ali)
            oss: '',
            headers: {},
            data: {},
            propsHttp: {
              url: 'link',
              name: 'name',
              res: 'data'
            },
            //普通图片上传
            action: '/api/localfiles/uploadPcFile',
            hide: true
          },
          {
            label: "活动规则",
            prop: "rule",
            type: "textarea",
            span: 24,
            minRows: 6,
            rules: [{
              required: true,
              message: "请输入活动规则",
              trigger: "blur"
            }],
            hide: true,
            maxlength: 200,
            showWordLimit: true
          },
          {
            label: "封面图",
            prop: "coverplan",
            rules: [{
              required: true,
              message: "请输入封面图",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            accept: "image/*",
            listType: 'picture-img',
            span: 8,
            propsHttp: {
              url: 'link',
              name: 'name',
              res: 'data'
            },
            fileSize: 500,
            action: '/api/localfiles/uploadPcFile',
            tip: '只能上传jpg/png文件，且不超过500kb',
            hide: true,
            uploadBefore: (file, done, loading, col) => {
              this.screenShotDialogVisible = true
              const fileReader = new FileReader()
              fileReader.onload = (res) => {
                // 给图片裁切传递参数
                this.imgUrl = res.target.result
              }
              fileReader.readAsDataURL(file)
              // 备份
              this._done = done
              this._uploadLoading = loading
              this.proportion = [118, 118]
            }
          },
          {
            label: "背景图",
            prop: "backgroundimage",
            span: 8,
            rules: [{
              required: true,
              message: "请输入背景图",
              trigger: "blur"
            }],
            type: 'upload',
            loadText: '附件上传中，请稍等',
            limit: 1,
            accept: "image/*",
            listType: 'picture-img',
            propsHttp: {
              url: 'link',
              name: 'name',
              res: 'data'
            },
            fileSize: 500,
            action: '/api/localfiles/uploadPcFile',
            tip: '只能上传jpg/png文件，且不超过500kb',
            hide: true,
            uploadBefore: (file, done, loading, col) => {
              this.screenShotDialogVisible = true
              const fileReader = new FileReader()
              fileReader.onload = (res) => {
                // 给图片裁切传递参数
                this.imgUrl = res.target.result
              }
              fileReader.readAsDataURL(file)
              // 备份
              this._done = done
              this._uploadLoading = loading
              this.proportion = [375, 200]
            }
          },
          {
            label: "发起人",
            prop: "initiator",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入发起反人	",
              trigger: "blur"
            }],
            maxlength: 100,
            showWordLimit: true
          },
          {
            label: "状态",
            prop: "status",
            search: true,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入状态",
              trigger: "blur"
            }],
            type: 'select',
            dicUrl: "/api/PcPublicService/GetDictionaryList?code=WENZHANGZHUANGTAI",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.zyhd_add, false),
        viewBtn: this.vaildData(this.permission.zyhd_view, false),
        delBtn: this.vaildData(this.permission.zyhd_delete, false),
        editBtn: this.vaildData(this.permission.zyhd_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    loadError(error) {
      this.$message({
        type: "error",
        message: error
      });
    },
    rowSave(row, done, loading) {
      if (!contrastTime(row.starttime,row.endtime)) {
        this.$message({
          type: "warning",
          message: "开始时间不可大于结束时间!"
        });
        loading();
        return 0
      }
      if (!contrastTime(row.endtime,row.matchtime)) {
        this.$message({
          type: "warning",
          message: "比赛时间不可小于报名截止时间!"
        });
        loading();
        return 0
      }
      row.id = row.id === '' ? '0' : row.id
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (!contrastTime(row.starttime,row.endtime)) {
        this.$message({
          type: "warning",
          message: "开始时间不可大于结束时间!"
        });
        loading();
        return 0
      }
      if (!contrastTime(row.endtime,row.matchtime)) {
        this.$message({
          type: "warning",
          message: "比赛时间不可小于报名截止时间!"
        });
        loading();
        return 0
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: this.ids});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    showCyjl(row) {
      this.activityId = row.id;
      //this.$refs.eps.onLoad({currentPage:1,pageSize:10});
      this.showMain = false;
    },
    showMainView() {
      this.showMain = true;
    },
    closeDialog(val){
      if(this._uploadLoading !== null){
        this._uploadLoading();
        this._uploadLoading = null
      }
      this.screenShotDialogVisible = val;
    },
    getImgURL(data){
      if(this._done !== null){
        this._done(data);
        this._done = null
      }
      this.closeDialog(false)
    }
  }
};
</script>

<style>
</style>
